package com.xaptul.docpreview.util.converter;

import java.io.File;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.document.DocumentFormat;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeConnectionProtocol;
import org.artofsolving.jodconverter.office.OfficeException;
import org.artofsolving.jodconverter.office.OfficeManager;

import com.xaptul.docpreview.util.abstra.Converter;
import com.xaptul.docpreview.util.exception.ConvertException;

@Supported({ "*.doc", "*.docx", "*.docm", "*.xls", "*.xlc", "*.xlm", "*.xlw",
		"*.xlsb", "*.xlsx", "*.xlsm", "*.rtf", "*.csv" })
public class Jodconverter implements Converter {

	private OfficeDocumentConverter converter;

	private DocumentFormat htmlFormat;

	private int timeout = 30000;

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public Jodconverter() {
		int processors = Runtime.getRuntime().availableProcessors();
		String[] pipeNames = new String[processors];
		for (int i = 0; i < pipeNames.length; i++) {
			pipeNames[i] = ("openOfficePipe" + i);
		}
		final OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
				.setConnectionProtocol(OfficeConnectionProtocol.PIPE)
				.setPipeNames(pipeNames).setTaskExecutionTimeout(this.timeout)
				.buildOfficeManager();
		officeManager.start();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				officeManager.stop();
			}
		});
		this.converter = new OfficeDocumentConverter(officeManager);
		this.htmlFormat = this.converter.getFormatRegistry()
				.getFormatByExtension("html");
	}

	public void convert(File infile, File outfile) throws ConvertException {
		if (outfile.exists())
			return;
		try {
			this.converter.convert(infile, outfile, this.htmlFormat);
		} catch (OfficeException e) {
			throw new ConvertException(e);
		}
	}
}